//
//  HWCustomRemarkSheet.m
//  HuaWan
//
//  Created by HuaWan  on 2022.
//  Copyright © 2022 HuaWan . All rights reserved.
//

#import "HWCustomRemarkSheet.h"

@implementation HWCustomRemarkSheet

- (void)awakeFromNib {
    [super awakeFromNib];
    // Do any additional setup after loading the view.
    [self.textView setContentOffset:CGPointZero animated:NO];
    self.textView.delegate = self;
}

- (void)setData:(id)data delegate:(id)delegate {
    _delegate = delegate;
    
    if ([data isKindOfClass:[HWCustomRemarkSheetModel class]]) {
        HWCustomRemarkSheetModel *model = data;
        _model = model;
        _icoImageView.image = [UIImage imageNamed:model.ico];
        _nameLabel.text = model.name;
        _placeholderLabel.text = model.tip;
        _textView.text = model.text;

        _placeholderLabel.hidden = model.text.length > 0 ? YES : NO;
        
        if (model.text.length > model.max.integerValue) {
            model.text = [model.text substringToIndex:model.max.integerValue];
        }
    }
}

- (void)textViewDidChange:(UITextView *)textView{
    _placeholderLabel.hidden = textView.text.length > 0 ? YES : NO;
    if (_delegate && [_delegate respondsToSelector:@selector(customRemarkSheet:textView:)]) {
        [_delegate customRemarkSheet:self textView:textView];
    }
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    _placeholderLabel.hidden = textView.text.length > 0 ? YES : NO;
    if (_delegate && [_delegate respondsToSelector:@selector(customRemarkSheet:textView:)]) {
        [_delegate customRemarkSheet:self textView:textView];
    }
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSString *new = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger res = [new length];
    
    _placeholderLabel.hidden = new.length > 0 ? YES : NO;

    if(res <= _model.max.integerValue){
        return YES;
    } else {
        _textView.text = [new substringToIndex:_model.max.integerValue - 1];
        return NO;
    }
}
 
- (IBAction)buttonAction:(UIButton *)sender {
    if (_delegate && [_delegate respondsToSelector:@selector(customRemarkSheet:buttonAction:)]) {
        [_delegate customRemarkSheet:self buttonAction:sender];
    }
}

@end



#pragma mark - Model

@implementation HWCustomRemarkSheetModel
    
+ (HWCustomRemarkSheetModel *)ittemModelWithIco:(NSString *)ico name:(NSString *)name text:(NSString *)text tip:(NSString *)tip max:(NSString *)max {
    HWCustomRemarkSheetModel *model = [HWCustomRemarkSheetModel new];
    model.ico = kSafeString(ico);
    model.name = kSafeString(name);
    model.text = kSafeString(text);
    model.tip = kSafeString(tip);
    model.max = kSafeString(max);
    return model;
}
    
@end
